package com.shixihub.browservice;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Objects;
import java.util.concurrent.ExecutionException;

/**
 * @author LiShixi 2021/4/15 3:28 上午
 */
@RestController
@RequestMapping("/img")
@Slf4j
public class BrowServiceController {


    @GetMapping("/screenshot")
    @ResponseBody
    public Object screenshot(@RequestPart(value = "url", required = false) String url) {
        final JvppeteerService jvppeteerService = new JvppeteerService();
        try {
            return jvppeteerService.screenshot(Objects.isNull(url) ? "https://cn.bing.com/" : url);
        } catch (InterruptedException | IOException | ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    @PostMapping(value = "/html")
    @ResponseBody
    public Object htmlToImg(@RequestPart("file") FilePart filePart) {
        try {
            Path tempFile = Files.createTempFile("htmlToImg", filePart.filename());

            AsynchronousFileChannel channel = AsynchronousFileChannel.open(tempFile, StandardOpenOption.WRITE);
            DataBufferUtils.write(filePart.content(), channel, 0)
                    .doOnComplete(() -> {
                        try {
                            channel.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    })
                    .doOnError(Throwable::printStackTrace)
                    .subscribe();

            final JvppeteerService jvppeteerService = new JvppeteerService();
            final String imgBase64 = jvppeteerService.screenshot(tempFile.toAbsolutePath().toString());
            log.debug("img base64={}", imgBase64);
            return Mono.just(imgBase64);

        } catch (IOException | ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * echarts出图
     * @param query
     * @return
     */
    @PostMapping("/echarts")
    @ResponseBody
    public String echartsConvert(@RequestBody(required = false) EchartsConvertQuery query) {
        Assert.isTrue(Strings.isNotBlank(query.getOption())||Strings.isNotBlank(query.getPageFunction()),
                "option和pageFunction二选一,pageFunction优先级高于option\n" +
                        "option: \"{xxx}\" // " +
                        "pageFunction:\"js脚本，完全自定义渲染逻辑，\n" +
                        "var chartDom = document.getElementById('canvas');//\"canvas\"是DOM容器的ID，固定的。\"");
        String option = "", pageFunction = "";

        if (Objects.nonNull(query.getPageFunction()) && Strings.isNotBlank(query.getPageFunction())) {
            pageFunction = query.getPageFunction();
        } else if (Objects.nonNull(query.getOption()) && Strings.isNotBlank(query.getOption())) {
            option = query.getOption();
        }

        return new JvppeteerService().echartsConvert(option, pageFunction,query.getDomId()).orElse("");
    }

}



